package com.rednote.common;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
public class Result<T> {
    private Integer code;
    private String msg;
    private T data;

    public Result(Integer code, String msg, T map) {
        this.code = code;
        this.msg = msg;
        this.data = map;
    }

    public Result() {

    }

    public static <T> Result<T> success(T data) {
        Result<T> r = new Result<>();
        r.setCode(200);
        r.setMsg("操作成功");
        r.setData(data);
        return r;
    }

    public static <T> Result<T> success(String msg, T data) {
        Result<T> r = new Result<>();
        r.setCode(200);
        r.setMsg(msg);
        r.setData(data);
        return r;
    }

    public static Result<?> fail(String msg) {
        Result<Object> r = new Result<>();
        r.setCode(400);
        r.setMsg(msg);
        return r;
    }

    public static Result<?> fail(Integer code, String msg) {
        Result<Object> r = new Result<>();
        r.setCode(code);
        r.setMsg(msg);
        return r;
    }

    // 链式方法 - 设置整个data对象
    public <R> Result<R> data(R data) {
        return new Result<>(this.code, this.msg, data);
    }

    // 链式方法 - 添加键值对到Map类型的data
    public Result<Map<String, Object>> data(String key, Object value) {
        Map<String, Object> map;
        if (this.data instanceof Map) {
            // 如果当前data已经是Map，直接使用
            @SuppressWarnings("unchecked")
            Map<String, Object> existingMap = (Map<String, Object>) this.data;
            map = new HashMap<>(existingMap);
        } else {
            // 否则创建新Map
            map = new HashMap<>();
            // 如果当前data不是null，将其作为特殊字段加入
            if (this.data != null) {
                map.put("result", this.data);
            }
        }
        map.put(key, value);
        return new Result<>(this.code, this.msg, map);
    }


}

